package cn.top.system.service.impl;

import cn.top.system.entity.SysMenu;
import cn.top.system.entity.TreeSelect;
import cn.top.system.mapper.SysMenuMapper;
import cn.top.system.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author tutu
 * @since 2024-09-09
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnMenus = new ArrayList<>();
        List<Long> menuIds = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        for (SysMenu menu : menus) {
            if (!menuIds.contains(menu.getParentId())) {
                recursionFn(menus,menu);
                returnMenus.add(menu);
            }
        }
        if (returnMenus.isEmpty())
        {
            returnMenus = menus;
        }
        return returnMenus;
    }

    @Override
    public List<TreeSelect> buildTreeSelect(List<SysMenu> menus) {
        List<SysMenu> sysMenus = buildMenuTree(menus);
        return sysMenus.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /*
        递归方法
     */
    private void recursionFn(List<SysMenu> menus, SysMenu m) {
        List<SysMenu> childrenMenus = findChildrenMenus(menus, m);
        m.setChildren(childrenMenus);
        for (SysMenu menu : childrenMenus) {
            if (findChildrenMenus(menus, menu).size() > 0) {
                recursionFn(menus,menu);
            }
        }
    }

    /*
        查找子菜单
     */
    private List<SysMenu> findChildrenMenus(List<SysMenu> menus, SysMenu menu) {
        List<SysMenu> childrenMenus = new ArrayList<>();
        for (SysMenu sysMenu : menus) {
            if (sysMenu.getParentId().longValue() == menu.getMenuId().longValue()) {
                childrenMenus.add(sysMenu);
            }
        }
        return childrenMenus;
    }
}
